# 成功调用9222端口
# 【下滑为后台运行，不用担心鼠标】
# 【为什么会有打开一个窗口？？？】【因为是打开端口的代码】【调试端口的代码会出错】
# 【先打开0812打开edge-sci登录-pdf模式【模板】【端口9222】】
# 【！！！已经在打开端口配制好pdf模式，所以调试时不必再配置！！！】
# 【getpaper_zh(paperurl)文章标题】
import os,json,re
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import pyautogui
from selenium.webdriver.edge.options import Options# 实现无可视化界面的操作,
# 下滑到某元素
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains#模拟鼠标滑动
import sys,traceback

#定义浏览器对象
options = Options()#定义一个option对象
# options.add_argument("headless")#实现无可视化界面的操作,无可视化界面（无头浏览器）
#第一次打开的
# options.add_argument("--remote-debugging-port=9222")
# 之后测试的
options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
'''
options.add_argument('--enable-print-browser')  # 启用PrintBrowser模式，其中所有内容都呈现为打印
options.add_argument('--kiosk-printing')  # 在打印预览中自动按下打印按钮
settings = {
    "recentDestinations": [
    {
        "id": "Save as PDF",
        "origin": "local"
    }
    ],
    "selectedDestinationId": "Save as PDF",
    "version": 2
}
prefs = {
    'printing.print_preview_sticky_settings.appState': json.dumps(settings),
    'savefile.default_directory': 'C:\\Users\\King\\Desktop'  # 下载文件保存的路径
}
options.add_experimental_option('prefs', prefs)
# options.add_argument('--remote-debugging-port=9222')
'''


driver= webdriver.Edge(options = options)


# driver = webdriver.Edge()
# driver.maximize_window()
# driver.set_window_size(800,750) # 设置浏览器大小 单位像素


# url="https://baidu.com"
# url="https://www.sciencedirect.com/science/article/pii/S1674200123001293"

def getpaper_zh(paperurl):
    driver.get(paperurl)
    sleep(1)
    # 先获取英文标题名
    try:
        papertitle=driver.find_element(By.CLASS_NAME,"title-text").text
    #     paperen = driver.page_source  # 获取网页源代码
    #     title1 = re.compile("<title>(.*)</title>")  # 通过正则表达式定位到文章标题
    #     title = title1.findall(a)[0][:-6]  # 切片去除无意义的后缀
        papertitle=papertitle.replace("/","")
        papertitle=papertitle.replace(":","")+"_zh"
        print("文章标题 "+papertitle)
    except Exception as e:
        print(e)
        print("获取文字标题出错")
        papertitle=paperurl.rsplit('/', 1)[1]+"_zh"#S000000013543
        print("文章标题 "+papertitle)
        
    sleep(0.5)
#     pyautogui.moveTo(25,150)
    pyautogui.moveTo(30,150)#30,150,win10
#     pyautogui.moveTo(400,150)
#     pyautogui.click()
    pyautogui.click()

    # 重新soup并下翻，成功获取
    for i in range(2):
        pyautogui.press("pagedown")
        sleep(0.2)
    #     pyautogui.press("pagedown")
    sleep(2)

    # 翻译
    print("即将翻译")
    pyautogui.press("home")
    sleep(1)
#     pyautogui.moveTo(400,150)
#     pyautogui.moveTo(25,150)
    pyautogui.moveTo(30,150)#win10
    pyautogui.rightClick()
    sleep(1)
    for i in range(9):#右键找到翻译,win10
        pyautogui.press('down')
#         sleep(0.1)
    pyautogui.press('enter')
    sleep(2)

    '''
    # //*[@id="cebib0010"]/h2
    loc = (By.XPATH,'//h2[text()="References"]')#根据文字查找【修改h2，References】
    a = driver.find_element(*loc)#find 元素对象
    print("找到测试元素")
    # 方法1、直接跳到目标元素【成功】
    driver.execute_script('arguments[0].scrollIntoView(false);',a)#flase底部对齐，默认true顶部对齐
    print("移动到元素element对象的“底端”与当前窗口的“底部”对齐")
    '''


    # 方法2、每次下滑500，直到目标元素【driver.execute_script(js)】
    max_scroll_times=30#【50太多。40可以】
    scroll_count=0
    js = "window.scrollBy(0, 600)"  # 向下滑动500个像素

    # driver.execute_script(js)
    # target_element=WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,'//h2[text()="References"]')))
    # target_element=
#     while driver.execute_script('windows.scrollTo(0,document.body.scrollHeight)'):
#     while WebDriverWait(driver,1).until(EC.presence_of_element_located((By.XPATH,'//li[text()="关于科学直通"]'))):#//*[@id="els-footer-about-science-direct"]/span
    while scroll_count < max_scroll_times:
    #     print("正在下滑500")
        driver.execute_script(js)
    #     sleep(0.5)
    #     scroll_count+=1 #以上根据次数下滑，成功
        
    #     if target_element.is_displayed():#即使还未出现，仍会运行
    #         print("窗口中出现元素")
    #         break 
        try:
    #         WebDriverWait(driver,10).until(EC.presence_of_element_located(loc))
#             WebDriverWait(driver,1).until(EC.presence_of_element_located((By.XPATH,'//*[@id="mathjax-container"]/div[2]/article/div[11]/span
            if WebDriverWait(driver,1).until(EC.presence_of_element_located((By.XPATH,'//h2[text()="确认"]'))):#//*[@id="aep-acknowledgment-id25"]/h2
                print("已经翻译至‘确认’")
                break 
            elif WebDriverWait(driver,1).until(EC.presence_of_element_located((By.XPATH,'//h2[text()="竞合利益声明"]'))):
                print("已经翻译至‘竞合利益声明’")
                break #跳出，继续下一步
            elif WebDriverWait(driver,1).until(EC.presence_of_element_located((By.XPATH,'//h2[text()="引用"]'))):
                print("已经翻译至‘引用’")
                break #跳出，继续下一步
            elif WebDriverWait(driver,1).until(EC.presence_of_element_located((By.XPATH,'//li[text()="关于科学直通"]'))):
                print("已经翻译至‘关于科学直通’")
                break #跳出，继续下一步
 
        except :
            scroll_count+=1 #以上根据次数下滑，成功
            pass
        
#         不了是否找到确认，在完成35次翻页后，直接打印
    try:
        print("开始打印")
#             vvv1="sci"
#             vvv1=papername
        if len(papertitle) > 70:
            print(">70")
            js1 = "document.title='"+papertitle[:70]+"';window.print();"
#             js1 = "document.title='"+"wenzhang"+"';window.print();"
#             pyautogui.hotkey("ctrl","p")保存文件名为中文标题
#             sleep(5)
#             js = "document.title='"+papertitle[:70]+"';window.print();"  # 保存文件的文件名是文章标题，使用js的window.print()调出打印窗口,避免使用ctrl+P
        else:
            print("<=70")
            js1 = "document.title='"+papertitle+"';window.print();"
#             pyautogui.hotkey("ctrl","p")
#             sleep(5)
        driver.execute_script(js1)
        pyautogui.hotkey("ctrl","p")#成功以papertitle!!!
        sleep(3)
#         if driver.execute_script(js1):
#             print("**********一篇成功***********")
#         else:
#             print("**********一篇失败***********")
#         sleep(1)
    except Exception as e:
        print(e)
#     print("打印成功")


# getpaper_zh(url)

# # 手动下载
# test_list=['https://www.sciencedirect.com/science/article/pii/S2213343717304943', 'https://www.sciencedirect.com/science/article/pii/S0032591017304953', 'https://www.sciencedirect.com/science/article/pii/S0022286013009812', 'https://www.sciencedirect.com/science/article/pii/S0921883113001891', 'https://www.sciencedirect.com/science/article/pii/S0022231318320490', 'https://www.sciencedirect.com/science/article/pii/S0030401815006781', 'https://www.sciencedirect.com/science/article/pii/S2405844019357226', 'https://www.sciencedirect.com/science/article/pii/S0022459612004628', 'https://www.sciencedirect.com/science/article/pii/S0021979716301370', 'https://www.sciencedirect.com/science/article/pii/S1876107017301220', 'https://www.sciencedirect.com/science/article/pii/S0959943611000435', 'https://www.sciencedirect.com/science/article/pii/S1759995422010282']

# test_list=['https://www.sciencedirect.com/science/article/pii/S1877705815007377', 'https://www.sciencedirect.com/science/article/pii/S0360319917320372', 'https://www.sciencedirect.com/science/article/pii/S0016236120310243']
# for a in test_list:
#     getpaper_zh(a)
    

'''
# # 获取目标元素
# target_element = driver.find_element(By.XPATH,'//h2[text()="References"]')#TRUE
# print("ref可见：")
# target_element = driver.find_element(By.ID,'sectitle0085')#TRUE
# //*[@id="sectitle0095"]竞合利益声明
target_element = driver.find_element(By.XPATH,'//h2[text()="竞合利益声明"]')#根据文字查找【修改h2，References】未出现会出错，
print(target_element.is_displayed()) #返回T,还是T，所以是指出现在网页中，非出现在视野中                                    
 '''                                    
                                     
                                     
                                     

# 判断是否可见
# target_visible=target_element.is_displayed()

# 移动到目标元素，确保它在可见区域内
# # 方法 1、 直接跳转
# actions=ActionChains(driver)
# actions.move_to_element(target_element).perform()


# print("显示")
# sleep(2)
# driver.close()

# cmd管理员》netstat -ano |findstr 9222
# TCP  127.0.0.1:9222   0.0.0.0:0   LISTENING 3108
# TCP  127.0.0.1:9222   127.0.0.1:49676   FIN_WATI_2 4924
# TCP  127.0.0.1:9222   127.0.0.1:50193   ESTABLISHED 3108
# TCP  127.0.0.1:49676   127.0.0.1:9222   CLOSE_WAIT 2600
# TCP  127.0.0.1:50193   127.0.0.1:9222   ESTABLISHED 6048
# 》tasklist |findstr 3108
# msedge.exe  3108 Console  1  89376K
# msedgedriver.exe  6048 Console  1  10376K
